package com.security.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 自定义用户登录
 * @author chengr
 *
 */
public class LoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
	//用户名  
    public static final String FORM_USERNAME_KEY = "username";  
    //密码  
    public static final String FORM_PASSWORD_KEY = "password";  
    //登录必须为post提交
    private boolean postOnly = true;
    
    public LoginAuthenticationFilter() {
		super();
	}
    /**
     * 自定义登录验证
     */
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {  
    	if (postOnly && !request.getMethod().equals("POST")) {  
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());  
        }  
        String username = obtainUsername(request);  
        String password = obtainPassword(request);  
        //用户信息认证
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);  
        setDetails(request, authRequest);  
        return this.getAuthenticationManager().authenticate(authRequest);  
    } 
	protected String obtainUsername(HttpServletRequest request) {  
        return request.getParameter(FORM_USERNAME_KEY)==null?"":request.getParameter(FORM_USERNAME_KEY).trim();  
    }
    protected String obtainPassword(HttpServletRequest request) {  
        return request.getParameter(FORM_PASSWORD_KEY)==null?"":request.getParameter(FORM_PASSWORD_KEY);  
    }
    protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {  
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));  
    }  

    public void setPostOnly(boolean postOnly) {  
        this.postOnly = postOnly;  
    }  
}
